package com.pro01.apirednote.controller;

import com.pro01.apirednote.pojo.Result;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/monitor")
@RequiredArgsConstructor
public class MonitoringController {
    
    private final MeterRegistry meterRegistry;
    

    @GetMapping("/performance")
    public Result<Map<String, Object>> getPerformanceMetrics() {
        Map<String, Object> metrics = new HashMap<>();
        
        // API请求数量
        double totalRequests = meterRegistry.get("api.request.count").counter().count();
        metrics.put("totalRequests", totalRequests);
        
        // API异常数量
        double totalExceptions = meterRegistry.get("api.request.exceptions").counter().count();
        metrics.put("totalExceptions", totalExceptions);
        
        // 成功率
        double successRate = totalRequests > 0 ? ((totalRequests - totalExceptions) / totalRequests) * 100 : 0;
        metrics.put("successRate", String.format("%.2f%%", successRate));
        
        // 系统信息
        Map<String, Object> systemInfo = new HashMap<>();
        systemInfo.put("processors", Runtime.getRuntime().availableProcessors());
        systemInfo.put("freeMemory", Runtime.getRuntime().freeMemory() / (1024 * 1024) + " MB");
        systemInfo.put("totalMemory", Runtime.getRuntime().totalMemory() / (1024 * 1024) + " MB");
        systemInfo.put("maxMemory", Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
        
        metrics.put("systemInfo", systemInfo);
        
        return Result.success(metrics);
    }
} 